<template>
    <div class="map-view-body">
        <div class="map-switch">
            <el-button round v-for="(item, idx) in sovereignts" :key="idx" @click="change(idx)"
                :type="state.activeSwitchIdx == idx ? 'primary' : ''">{{ item.name }}</el-button>
        </div>
        <div ref="mapView" class="map-view"></div>
    </div>
</template>

<script setup lang="ts" name="mapView">
import worldJson from '@/utils/worldGeo.json'
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from "vue";
import * as L from 'leaflet';
import homeConfig from '@/utils/homeConfig';
import globalPaymentConfig from '@/utils/globalPayment';

type MapType = 'home' | 'globalCollectionPayout'

const props = defineProps<{ mapType: MapType }>()
const { mapType } = props

const state = reactive({
    activeSwitchIdx: 0
})

interface SovereigntsObj {
    name: string;
    //
    toggle: boolean;
    // 需要展示的国家
    havySovereignts: string[];
}

// 切换计算得数据
const sovereignts = computed((): SovereigntsObj[] => {
    return mapType == 'home' ? homeConfig.gloablPayment.mapData : globalPaymentConfig.gloablCollectionPayout.mapData
})

function change(index: number) {
    state.activeSwitchIdx = index
    geoJsonLayer.setStyle(style)
}

const mapView = ref()
let map: L.Map
let geoJsonLayer: L.GeoJSON

// geojson
// https://geojson-maps.kyd.au/
// https://github.com/Surbowl/world-geo-json-zh
// leaflet typescript 支持： https://www.jianshu.com/p/66c2962d1dd0
// leaflet 中文文档： https://www.leafletjs.com.cn/

// 页面渲染完成，dom渲染完成执行
nextTick(() => {
    let mapOptions: L.MapOptions = {
        // 不显示缩放控件
        zoomControl: false,
        // 不显示版权信息
        attributionControl: false,
        // 缩放倍数
        zoomSnap: 0.2,
        // 不允许拖动
        dragging: false,
        // 不允许双击放大
        doubleClickZoom: false,
        // 不允许滚轮放大
        scrollWheelZoom: false,
        // 不允许键盘操作
        keyboard: false,
    }

    // 设置地图元素，中心点和缩放级别
    map = L.map(mapView.value, mapOptions)

    let geoObj = worldJson as GeoJSON.GeoJsonObject
    // geojson图层
    geoJsonLayer = L.geoJson(geoObj, { style, onEachFeature }).addTo(map);

    // 鼠标悬停时的高亮事件
    function highlightFeature(e: L.LeafletMouseEvent) {
        // 悬停的图层
        let layer = e.target as L.Path
        // 图层样式
        layer.setStyle({
            fillColor: '#f3f4fe',
            fillOpacity: 0.7
        });
    }

    // 鼠标离开时的重置事件
    function resetHighlight(e: L.LeafletMouseEvent) {
        // 重设图层样式到默认状态
        geoJsonLayer.resetStyle(e.target);
    }

    function clickFeature(e: L.LeafletMouseEvent) {
        let layer = e.target
        let name_zh = layer.feature.properties.name_zh ?? ''
        // map.openPopup(name_zh, e.latlng)

        // 弹窗设置
        let popOptions: L.PopupOptions = {
            // 自动关闭
            autoClose: true,
            // 不展示关闭
            closeButton: false,
            // pop类名
            className: 'popup'
        }
        L.popup(popOptions)
            .setLatLng(e.latlng)
            .setContent(`<p>Hello ${name_zh}!<br />This is a nice popup.</p>`)
            .openOn(map);
    }

    // 每个图层设置
    function onEachFeature(feature: GeoJSON.Feature, layer: L.Layer) {
        layer.on({
            // 高亮
            mouseover: highlightFeature,
            // 重置
            mouseout: resetHighlight,
            // 点击了图层
            // click: clickFeature
        })
    }

    resetMapScale()
})

function resetMapScale() {
    let width = window.innerWidth
    let rate = 0.0014
    let heightRate = 0.5
    if (width > 1300) {
        width = 1300
    }
    else if (width < 650) {
        rate = 0.001
        heightRate = 0.6
    }
    mapView.value.style.height = width*heightRate + 'px'    
    
    map.setView([45, 0], width*rate);
}

// 填充颜色为黑色的区域
function style(feature: GeoJSON.Feature | undefined) {
    // 国家
    let name_en = feature?.properties?.name_en as string || ''
    let currentObj = sovereignts.value[state.activeSwitchIdx]
    let contained = currentObj.havySovereignts.includes(name_en)
    if (currentObj.toggle) {
        contained = !contained
    }

    return {
        // 填充颜色
        fillColor: contained ? '#5a5b60' : '#d1d9dc',
        // 边框线线宽
        weight: 1,
        // 边框透明度
        opacity: 1,
        // 边框颜色
        color: '#c4c4c4',
        // 虚线样式
        // dashArray: '3',
        // 填充透明度
        fillOpacity: 1
    };
}

onMounted(() => {
    window.addEventListener('resize', resetMapScale)
})

onUnmounted(() => {
    window.removeEventListener('resize', resetMapScale)
})

</script>

<style scoped>

.map-view-body {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2rem;
}

.map-switch {
    margin: 0 auto;
}

.map-view {
    width: 100%;
    background: #fff;
}

@media (max-width: 650px) {
    /* .map-view {
        height: 400px;
    } */
}
</style>